<template>
  <v-main>
    <v-app-bar
        flat
        fixed
        align="center"
        height="60px"
        color="secondary"
    >
      <v-container>
        <v-row justify="center" class="py-0">
          <v-col cols="3" class="text-left pl-0">
            <v-btn icon @click="$router.back()" class="ml-n3" >
              <v-icon color="lighten-1" >mdi-arrow-left</v-icon>
            </v-btn>
          </v-col>
          <v-col cols="6">
            <div class="mt-3">
              心得笔记
            </div>
          </v-col>
          <v-col cols="3" class="text-right pr-0">
            <v-btn icon class="mr-n3" @click="commit">
              <v-icon color="lighten-1" size="30">mdi-check</v-icon>
            </v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-app-bar>
    <v-container class="mt-15">
      <v-row>
        <v-col class="py-0">
          <v-text-field
              ref="title"
              :rules="[rules.required,rules.maxLength(30)]"
              label="标题"
              v-model="form.title"
              hint="不超过30字"
          ></v-text-field>
        </v-col>
      </v-row>
      <v-row>
        <v-col class="py-0">
          <v-combobox
              ref="tags"
              v-model="chips"
              :rules="[rules.required,rules.maxLength(5)]"
              chips
              clearable
              label="添加标签"
              multiple
              hint="输入后回车添加标签"
              counter="5"
          >
            <template v-slot:selection="{ attrs, item, select, selected }">
              <v-chip
                  v-bind="attrs"
                  :input-value="selected"
                  close
                  @click="select"
                  @click:close="remove(item)"
              >
                {{ item }}
              </v-chip>
            </template>
          </v-combobox>
        </v-col>
      </v-row>
    </v-container>
    <v-container>
      <quill-editor
          v-model="content"
          :options="editorOption"
          class="editor"
          ref="myQuillEditor"
          @change="onChange"
      />
      <div class="v-counter theme--light text-right mt-2 " :class="contentCounter>300?'red--text':''">{{contentCounter}} / 300</div>
    </v-container>

  </v-main>

</template>

<script>
import {baseUrl, imgPrefixUrl} from "../myConfig";
import {Quill,quillEditor} from "vue-quill-editor";
import {ImageExtend, QuillWatch} from "quill-image-super-solution-module";
import {printMsg, rules,utf8_to_b64} from "../util/util";

Quill.register("modules/ImageExtend", ImageExtend);

export default {
  name: "newArticle",
  components:{quillEditor},
  data: () => ({
    chips: [],
    rules:rules,
    contentCounter:0,
    content: '',
    form:{
      title:'',
      content:'',
      type:'article',
      publisher:'',
      tags:'',
    },
    // 富文本框参数设置
    editorOption: {
      modules: {
        ImageExtend: {
          loading: true,
          name: "img",
          size: 5,
          action: baseUrl + "file/saveImageFD",
          accept: "image/jpg, image/png, image/gif, image/jpeg",
          response: (res) => {
            printMsg(res,this)
            return baseUrl + imgPrefixUrl + res;
          },
          headers: (xhr) => {
            xhr.setRequestHeader("Authorization", window.localStorage.getItem("token"));
          },
          sizeError: () => {
            alert("图片大小超过 5 M");
          },

        },
        toolbar: {
          container: [
            [{'size': ['small', false, 'large']}],
            ['bold', 'italic'],
            [{'header': 1}, {'header': 2}],
            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'color': []}, {'background': []}],
            [{'align': []}],
            ['clean'],
            ["link","image", "video"]
          ],
          handlers: {
            image: function () {
              QuillWatch.emit(this.quill.id);
            },
          },

        },
      }
    }
  }),
  methods: {
    processContent(){
      // 处理content中的图片和链接的url
      this.form.content = this.content.replaceAll('target="_blank"','target="_self"')
      this.form.content = this.form.content.replaceAll(baseUrl+imgPrefixUrl,'')
      // this.form.content = this.form.content.replace(/src="(.*?)"/,`src="${baseUrl+imgPrefixUrl}$1"`)
    },
    remove(item) {
      this.chips.splice(this.chips.indexOf(item), 1)
      this.chips = [...this.chips]
    },
    onChange(val){
      this.contentCounter = val.quill.getLength()-1
    },
    commit(){
      this.processContent()
      printMsg(this.form.content,this)

      //校验表单
      if (!this.$refs['title'].validate(true) || !this.$refs['tags'].validate(true)){
        return;
      }
      if (this.contentCounter>300){
        this.$emit('toast','文章内容太长啦')
        return
      }else if (this.contentCounter===0){
        this.$emit('toast','文章内容不能为空')
        return
      }

      //组装tags
      if (this.chips.length>0){
        this.form.tags = ','+this.chips.join(',')+','
      }else{
        this.$emit('toast','请选择关联的商品')
        return
      }
      // 对内容进行base64编码
      if (this.form.content){
        this.form.content = utf8_to_b64(this.form.content)
      }

      let data = this.form

      this.$http.post('article/addArticle', data).then(res => {
        this.$emit('toast','保存成功')
        this.$router.back()
      }).catch(res => {
        this.$emit("toast",res.msg)
      })
    },
  },
  beforeMount() {
    this.form.publisher =this.$store.state.uid
  }

}
</script>

<style scoped>
</style>
